﻿using UnityEngine;
using System.Collections;

public class RotateWithGesture : MonoBehaviour {

    // Use this for initialization
    public GameObject GestureObject;
    private GestureSweep gesture;
    private bool lastTracedState = false;
    private float beginAngle = 0;
    private float beginValue = 0;

    private int skipFrameToBegin = 0;

    void Start () {
        if (GestureObject)
        {
            gesture = GestureObject.GetComponent<GestureSweep>();
        }       
    }
	
	// Update is called once per frame
	void Update () {
        if (GestureObject!=null && gesture!=null)
        {
            Explosion explosion = GetComponent<Explosion>();
            if (explosion == null)
                return;
            if( lastTracedState != gesture.bTraced )
            {
                skipFrameToBegin = 15;
            }
            skipFrameToBegin-=1;
            if(skipFrameToBegin  == 0 )
            {
                beginAngle = explosion.Angle;
                beginValue = gesture.fValue;
            }
            

            if (gesture.bTraced && (skipFrameToBegin < 0))
            {
                explosion.RotateAutomatic = false;
                float value = (gesture.fValue - beginValue) / (gesture.fMaxValue - gesture.fMinValue);
                 
                explosion.Angle = beginAngle + 360 - (value * 360.0f);
                explosion.Angle = explosion.Angle % 360.0f;

                //Debug.Log(string.Format("begin Angle = {0} , value = {1}, Angle = {2}", beginAngle, value, explosion.Angle));
            }
            else
            {
                explosion.RotateAutomatic = true;
                //explosion.rotationRpm = 0.05f;
            }
            lastTracedState = gesture.bTraced;

        }
    }
}
